import { createStore } from "vuex";
import Stomp from 'stompjs';
import SockJS from "sockjs-client/dist/sockjs.min.js";
import { ElMessageBox } from 'element-plus';
 
import { base, deleteRequest, getRequest } from "@/stores/api";
import { useRoute } from 'vue-router'

const route = useRoute()
const store = createStore({
  state: () => ({
    newRoutes: [],
    yuanRoutes: [],
    friendStatus: {},
    routes: [],
    sessions: {},
    currentAdmin: JSON.parse(window.localStorage.getItem('user')),
    admins: [],
    tmpAdmins: [],
    allAdmins: [],
    isDot: {},
    currentSession: null,
    filterKey: '',
    stomp: null,
    canSend: false
  }),
  mutations: {
    initRoutes(state, data) {
      console.log(data);
      state.routes = data;
    },
    setFriendStatus(state, friendList) {
      state.friendStatus = friendList


    },
    INIT_CURRENTAdmin(state, admin) {
      state.currentAdmin = admin;
    },

    changeCurrentSessionId(state, currentSession) {
      state.currentSession = currentSession;
      state.isDot[state.currentAdmin.userInfo.username + '#' + state.currentSession.username] = 0;

    },
    addMessage(state, msg) {
      console.log('add');
      let mss = state.sessions[state.currentAdmin.userInfo.username + '#' + msg.to];
      if (!mss) {
        state.sessions[state.currentAdmin.userInfo.username + '#' + msg.to] = [];
      }
      state.sessions[state.currentAdmin.userInfo.username + '#' + msg.to].push({
        content: msg.content,
        date: new Date(),
        self: !msg.notSelf
      });
    },
    INIT_DATA(state) {
      let data = window.localStorage.getItem('vue-chat-session');
      if (data) {
        state.sessions = JSON.parse(data);
      }
    },
    INIT_ADMIN(state, data) {
      state.admins = data;
      state.tmpAdmins = data;
    },
    INIT_ADMIN_SEARCH(state, data) {
      state.allAdmins = data
    }
  },
  actions: {
    connect(context) {
      if (context.state.stomp && context.state.stomp.connected) {
        console.log('Stomp already connected');
        return;
      } 
        context.state.stomp = Stomp.over(new SockJS(base + '/ws/ep'));


      let token = window.localStorage.getItem("token");
      console.log(token);
      let authToken =  token;
      context.state.stomp.connect({ 'Auth-Token': authToken }, success => {
        // 判断用户是否在线
        context.state.stomp.subscribe('/queue/friendStatus', message => {
          console.log('listen-----');
          const friendList = JSON.parse(message.body)

          console.log(friendList);
          store.commit('setFriendStatus', friendList)
        })
        // setInterval(() => {
        //   const friend = { id: context.state.currentAdmin.userInfo.username, isOnline: true, lastHeartbeatTime: Date.now() }
        //   context.state.stomp.send('/addFriendStatus', {}, JSON.stringify(friend))
        //   context.state.stomp.send('/checkFriendStatus');
        // }, 2500);
        // 向后端发送好友状态信息


        context.state.stomp.subscribe('/user/queue/chat', msg => {
          const audio = new Audio('/src/assets/di.mp3');
          audio.play().catch(error => {
            console.error('播放失败:', error);
          });;
          console.log('listen-----');
          let receiveMsg = JSON.parse(msg.body);
          console.log(receiveMsg);
          let isUser = '';
          if (receiveMsg.order != null) {
            const order = JSON.parse(JSON.stringify(receiveMsg.order));
            isUser = '用户';
            receiveMsg.content = '订单号:' + order.id + '催单了';
          }
          if (!context.state.currentSession || receiveMsg.from != context.state.currentSession.username) {
            console.log('sssssss');
            ElNotification.info({
              title: '【' + isUser + receiveMsg.fromNickName + '】发来一条消息',
              message: receiveMsg.content.length > 25 ? receiveMsg.content.substr(0, 25) + "..." : receiveMsg.content,
              position: 'bottom-right',
              duration: 0,
            });
            var val = context.state.isDot[context.state.currentAdmin.userInfo.username + '#' + receiveMsg.from];
            if (val != undefined) {
              context.state.isDot[context.state.currentAdmin.userInfo.username + '#' + receiveMsg.from] = val + 1;
            } else {
              context.state.isDot[context.state.currentAdmin.userInfo.username + '#' + receiveMsg.from] = 1;
            }
          }
          receiveMsg.notSelf = true;
          receiveMsg.to = receiveMsg.from;
          context.commit('addMessage', receiveMsg);
        })
      }, error => {
      })
    },
    initData(context) {
      context.commit('INIT_DATA');
      context.currentAdmin = JSON.parse(window.localStorage.getItem('user'));
      let url = '/chat/all';
      getRequest(url).then(resp => {
        if (resp) {
          context.commit('INIT_ADMIN', resp.data[0]);
          context.commit('INIT_ADMIN_SEARCH', resp.data[1]);
        }
      })
    }
  },


})
import { watch } from 'vue'; // 引入 watch 函数

watch(
  () => store.state.sessions,
  (val) => {
    // console.log('CHANGE: ', val);
    // console.log('CHANGE: ', JSON.stringify(val));
    window.localStorage.setItem('vue-chat-session', JSON.stringify(val));
    // 监控太慢了只能进行实时前端操作数据，如果发送请求会丢失监听到的数据
  },
  { deep: true } // 这个是用来开启深度监测的选项
);

export default store;